const fs = require('fs');
const express = require('express');
const morgan = require('morgan');
const AppError = require('./utils/appError');
const globalErrorHandler = require('./controllers/errorController');
//middleware
const rateLimit = require('express-rate-limit');
const hpp = require('hpp');
const helmet = require('helmet');
const mongoSanitize = require('express-mongo-sanitize');
const xss = require('xss-clean');
const tourRouter = require('./routes/tourRoutes');
const userRouter = require('./routes/userRoutes');
const reviewRouter = require('./routes/reviewRoutes');
const favoriteNameRouter = require('./routes/favoriteNameRoutes');
const videoRouter = require('./routes/videoRoutes');
const imageRouter = require('./routes/imgRoutes');
const carouselRouter = require('./routes/carouselRoutes');

const multer = require('multer'); //file
//解决跨域
const cors = require('cors');
const app = express();
app.use(
  cors({
    origin: true, // 允许来自任意源的请求
    methods: ['GET', 'POST', 'PUT', 'DELETE'], // 允许的 HTTP 方法
    allowedHeaders: ['Content-Type', 'Authorization'], // 允许的请求头
  })
);
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', '*'); // 允许来自任意源的跨域请求
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE'); // 允许的 HTTP 方法
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // 允许的请求头
  next();
});

//GLOBAL MIDDLEWARE
//1)Set security HTTP headers
// app.use(helmet());
//跨域问题，安全性问题加强

let objMulter = multer({
  dest: './public/upload',
  fileFilter(req, file, callback) {
    file.originalname = Buffer.from(file.originalname, 'latin1').toString(
      'utf8'
    );
    //solve the 乱码问题
    callback(null, true);
  },
});
//实例化multer，传递的参数对象，dest表示上传文件的存储路径
app.use(objMulter.any()); //any表示任意类型的文件
// app.use(objMulter.image())//仅允许上传图片类型
app.use(express.static('./public'));
//将静态资源托管，这样才能在浏览器上直接访问预览图片或则html页面

//2)Development logging//to show more msg
if (process.env.NODE_ENV === 'development') {
  app.use(morgan('dev'));
}

//3)Limit requests from same API
const limiter = rateLimit({
  max: 10000,
  windowMs: 60 * 60 * 1000,
  message: 'Too many request from this ip in an hour',
});
app.use('/api', limiter);

//4)Body parser,reading data from body into  req.body
app.use(express.json({ limit: '10kb' }));
//can show the req.body {the req.json}

//Data sanitization against NoSQL query injection
app.use(mongoSanitize());
//Data sanitization against XSS
app.use(xss());
//like HTML

//Prevent parameter pollution
app.use(
  hpp({
    whitelist: [
      'duration',
      'ratingsAverage',
      'ratingsQuantity',
      'price',
      'difficulty',
      'maxGroupSize',
    ],
  })
);

//Test middleware
app.use((req, res, next) => {
  req.requestTime = new Date().toISOString();
  next();
});
app.use(express.static(`${__dirname}/public`));

//(3):ROUTES
app.use('/api/v1/tours', tourRouter);
app.use('/api/v1/users', userRouter);
app.use('/api/v1/review', reviewRouter);
app.use('/api/v1/favorite', favoriteNameRouter);
app.use('/api/v1/video', videoRouter);
app.use('/api/v1/uploadImage', imageRouter);
app.use('/api/v1/carousel', carouselRouter);
app.all('*', (req, res, next) => {
  next(new AppError(`Can't find ${req.originalUrl} on this server`, 404));
});
app.use(globalErrorHandler);

module.exports = app;

////////////////////////////////////////

// const { query } = require('express');
// const fs = require('fs');
// const http = require("http")
// const url = require("url")
// const tempOverview = fs.readFileSync(`${__dirname}/templates/overview.html`, 'utf-8')
// const tempCard = fs.readFileSync(`${__dirname}/templates/card.html`, 'utf-8')
// const tempProduct = fs.readFileSync(`${__dirname}/templates/product.html`, 'utf-8')
// const replaceTemplate  = require(`${__dirname}/modules/replaceTemplate.js`)
// const slugify = require('slugify')
// /////////////////////////////////
// // FILES
// const data = fs.readFileSync(`${__dirname}/dev-data/data.json`, 'utf-8')
// const dataObj = JSON.parse(data)

// const slugs = dataObj.map(el=>slugify(el.productName,{lower:true}))
// console.log(slugs)
// /////////////////////////////////
// // SERVER
// const server = http.createServer((req, res) => {
//   const {query,pathname }= url.parse(req.url,true)
//   console.log(pathname)
//   //true表示解析为对象
//   //eg: query:{id:"0"} ,pathname:"product"

//   if (pathname==='/' || pathname === '/overview' ) {
//     res.writeHead(200,{"Content-type":'text/html'})
//     const cardsHtml = dataObj.map(el=>
//       replaceTemplate(tempCard,el)
//     ).join('');
//     // console.log(cardsHtml)
//     const output = tempOverview.replace('{%PRODUCT_CARDS%}', cardsHtml)
//     res.end(output)

//   } else if (pathname === '/api') {

//     res.writeHead(200, { "Content-type": "application/json" })
//     // console.log(productData)

//     res.end(data);

//   }else if(pathname==='/product'){
//     res.writeHead(200,{'Content-type':'text/html'});
//     const product = dataObj[query.id];
//     const output = replaceTemplate(tempProduct,product);
//     res.end(output)
//     // res.end("THIS IS PRODUCT")
//   }
//   else {
//     res.writeHead(404, {
//       'Content-type': 'text/html',
//       'my-own-header': 'hello-world'

//     })
//     res.end('<h1>Page not found!</h1>');

//   }

// })
// server.listen(8000, "127.0.0.1", () => {
//   console.log("success")
// })

//////////////////////////
// var createError = require('http-errors');
// var express = require('express');
// var path = require('path');
// var cookieParser = require('cookie-parser');
// var logger = require('morgan');

// var indexRouter = require('./routes/index');
// var usersRouter = require('./routes/users');

// var app = express();

/**
 * 测试DataAccess
 */
//  var MySqlHelper = require('./common/DataAccess');
//  var ds = new MySqlHelper();
//  console.log("11")
//  ds.GetTable("select 1+1 as sam").then(dt => {
//  console.log(dt+"111");
//  }).catch(err => {
//  console.log(err);
//  });

// view engine setup
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'jade');

// app.use(logger('dev'));
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
// app.use(cookieParser());
// app.use(express.static(path.join(__dirname, 'public')));

// app.use('/', indexRouter);
// app.use('/users', usersRouter);

// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
//   next(createError(404));
// });

// // error handler
// app.use(function(err, req, res, next) {
//   // set locals, only providing error in development
//   res.locals.message = err.message;
//   res.locals.error = req.app.get('env') === 'development' ? err : {};

//   // render the error page
//   res.status(err.status || 500);
//   res.render('error');
// });

// module.exports = app;
